﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace JinYuan.Helper
{
    public class DeleteLog
    {
        public static void Start(string[] strPata, short[] methodSelect)
        {
            Init(strPata, methodSelect);
        }

        private static void Init(string[] strPata, short[] methodSelect)
        {
            Task.Run(() =>
            {
                try
                {
                    while (true)
                    {
                        for (int i = 0; i < strPata.Length; i++)
                        {
                            switch (methodSelect[i])
                            {
                                case 0:
                                    bool b = DeleteDirectory(strPata[i], 30); //删除该目录下 超过 30天的文件
                                    if (b)
                                    {
                                        LogHelper.Instance.WriteLog($"已清除路径:{strPata[i]},30天内过期日志");
                                    }
                                    break;
                                case 1:
                                    bool c = DeleteFile(strPata[i], 30);
                                    if (c)
                                    {
                                        LogHelper.Instance.WriteLog($"已清除路径:{strPata[i]},30天内过期日志");
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //24小时清一次
                        Thread.Sleep(1000 * 60 * 60 * 24);
                    }
                }
                catch (Exception e)
                {
                    Thread.Sleep(1000 * 60 * 60 * 28);
                }
            });
        }

        public static void DeleteDirectory(string target_dir)
        {
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs = Directory.GetDirectories(target_dir);
            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }
            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }
            Directory.Delete(target_dir, false);
        }

        private static bool DeleteDirectory(string fileDirect, int saveDay)
        {
            try
            {
                if (!Directory.Exists(fileDirect))
                {
                    LogHelper.Instance.WriteLog($"{fileDirect},文件夹不存在");
                    return false;
                }
                DateTime nowTime = DateTime.Now;
                string[] files = Directory.GetFiles(fileDirect, "*.*", SearchOption.AllDirectories);  //获取该目录下所有 .txt文件 
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    TimeSpan t = DateTime.Now - fileInfo.CreationTime;  //当前时间  减去 文件创建时间
                    int day = t.Days;
                    if (day > saveDay)   //保存的时间，单位：天
                    {
                        if (IsOccupy(fileInfo.FullName)) //判断文件是否被占用
                        {
                            if (fileDirect.Contains("Mes"))//MesLogs
                            {
                                Directory.Delete(fileInfo.Directory.Parent.FullName, true);
                                return true;
                            }
                            else//其它
                            {
                                Directory.Delete(fileInfo.Directory.FullName, true);
                                return true;
                            }
                        }
                        else
                        {
                            LogHelper.Instance.WriteLog($"{fileInfo.FullName},文件被占用，无法操作!");
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.Instance.WriteLog($"APILog日志删除异常,异常原因:{err}");
            }
            return false;
        }

        public static bool DeleteFile(string fileDirect, int saveDay)
        {
            try
            {
                if (!Directory.Exists(fileDirect))
                {
                    LogHelper.Instance.WriteLog($"{fileDirect},文件夹不存在");
                    return false;
                }
                DateTime nowTime = DateTime.Now;
                string[] files = Directory.GetFiles(fileDirect, "*.*", SearchOption.AllDirectories);  //获取该目录下所有 .txt文件 
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);

                    TimeSpan t = DateTime.Now - fileInfo.LastWriteTime;// fileInfo.CreationTime;  //当前时间  减去 文件创建时间
                    int day = t.Days;
                    if (day > saveDay)   //保存的时间，单位：天
                    {
                        if (IsOccupy(fileInfo.FullName)) //判断文件是否被占用
                        {
                            System.IO.File.Delete(fileInfo.FullName); //删除文件
                        }
                        else
                        {
                            LogHelper.Instance.WriteLog($"{fileInfo.FullName},文件被占用，无法操作!");
                        }
                    }
                }
                return true;
            }
            catch (Exception err)
            {
                LogHelper.Instance.WriteLog($"Logs日志删除异常,异常原因:{err}");
            }
            return false;
        }

        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static bool IsOccupy(string file)
        {
            bool result = true; //默认状态此文件未被占用
            try
            {
                //string vFileName = @"c:\temp\temp.bmp";
                string vFileName = file;
                if (!System.IO.File.Exists(vFileName))
                {
                    //Logger.Info("文件都不存在!");
                    result = false;
                }
                IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (vHandle == HFILE_ERROR)
                {

                    //Log4Helper.WriteLog("文件被占用！", "错误提示");
                    result = false;
                }
                CloseHandle(vHandle);
                // Log4Helper.WriteLog("没有被占用！", "错误提示");


            }
            catch (Exception err)
            {
                result = false;
                //Log4Helper.WriteLog("判断文件是否被占用", err);


            }
            return result;
        }

    }
}
